package com.neepu.controller;

import com.neepu.pojo.Document;
import com.neepu.pojo.Teacher;
import com.neepu.pojo.User;
import com.neepu.service.DocumentService;
import com.neepu.service.TeacherService;
import com.neepu.service.UserService;
import com.neepu.util.annotation.ArchivesLog;
import com.neepu.util.common.MyFileUtil;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.List;

@Controller
public class InfoManagerController {


    @Autowired
    private UserService userService;

    @Autowired
    private TeacherService teacherService;

    @Autowired
    private DocumentService documentService;


    // 教师信息
    @ArchivesLog(operteContent = "查看教师信息")
    @RequestMapping(value = "/info/teacher")
    public String teacher(Model model,String content){

        if (content!=null&&!content.equals("")){
            List<Teacher> list = teacherService.getTeacherByContent(content);
            model.addAttribute("list",list);
            return "infomanage/teacher";
        }else {
            List<Teacher> list = teacherService.getTeacher();
            model.addAttribute("list",list);
            return "infomanage/teacher";
        }
    }

    //学生信息
    @ArchivesLog(operteContent = "查看学生信息")
    @RequestMapping(value = "/info/student")
    public String student(Model model,String content){
        if (content!=null&&!content.equals("")){
            List<User> list = userService.finUserByContent(content);
            model.addAttribute("list",list);
            return "infomanage/student";
        }else{
            List<User> list = userService.finUserByRole();
            model.addAttribute("list",list);
            return "infomanage/student";
        }
    }

    // 培养方案
    @ArchivesLog(operteContent = "查看培养方案")
    @RequestMapping(value = "/info/programme")
    public String programme(Model model,String content){
        if (content!=null&&!content.equals("")){
            List<Document> list = documentService.findAllDocumentByContent(content);
            model.addAttribute("list",list);
            return "infomanage/programme";
        }else {
            List<Document> list = documentService.getDocument();
            model.addAttribute("list",list);
            return "infomanage/programme";
        }
    }

    // 跳转上传培养方案页面
    @RequestMapping("/updateDocument")
    public String updateDocument(){
        return "infomanage/add";
    }

    @ArchivesLog(operteContent = "上传文件")
    @RequestMapping(value="/document/add",method= RequestMethod.POST)
    public ModelAndView add(ModelAndView mv, @ModelAttribute Document document, Integer id, HttpSession session,String filename){
        if(id!=null){
            document.setFilename(filename);
            createFile(document, session);
            documentService.update_DocumentInfo(document);
        }else{
            createFile(document, session);
            documentService.insert_DocumentInfo(document);
        }
        mv.setViewName("redirect:/info/programme");
        return mv;
    }

    private void createFile(@ModelAttribute Document document, HttpSession session) {

        String path = session.getServletContext().getRealPath("files/");
        String filename = document.getFile().getOriginalFilename();

        try {
            MyFileUtil.uploadFile(document.getFile().getBytes(), path, filename);
        } catch (Exception e) {
            System.out.println("上传文件异常");
        }
        document.setFilename(filename);
    }

    /**
     * 处理文档下载请求
     * @param  ， 1表示跳转到修改页面，2表示执行修改操作
     * */

    @ArchivesLog(operteContent = "下载文件")
    @RequestMapping(value="/document/downLoad")
    public ResponseEntity<byte[]> downLoad(
            Integer id,
            HttpSession session) throws Exception{
        // 根据id查询文档
        Document target = documentService.get_DocumentInfo(id);
        String fileName = target.getFilename();
        // 上传文件路径
        String path = session.getServletContext().getRealPath(
                "/files");
        // 获得要下载文件的File对象
        File file = new File(path+"/"+ fileName);
        // 创建springframework的HttpHeaders对象
        HttpHeaders headers = new HttpHeaders();
        // 下载显示的文件名，解决中文名称乱码问题
        String downloadFielName = new String(fileName.getBytes("UTF-8"),"iso-8859-1");
        // 通知浏览器以attachment（下载方式）打开图片
        headers.setContentDispositionFormData("attachment", downloadFielName);
        // application/octet-stream ： 二进制流数据（最常见的文件下载）。
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        // 201 HttpStatus.CREATED
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
                headers, HttpStatus.CREATED);
    }

    // 删除文件
    @ArchivesLog(operteContent = "删除文件")
    @RequestMapping(value="/document/delete",method=RequestMethod.GET)
    public void delete(Integer id){
        if(id!=null){
            documentService.delete_DocumentInfo(id);
        }
    }

    // 编辑文件
    @ArchivesLog(operteContent = "编辑文件")
    @RequestMapping(value="/document/edit",method=RequestMethod.GET)
    public String edit(Model model,Integer id){
        if(id!=null){
            Document list = documentService.get_DocumentInfo(id);
            model.addAttribute("list",list);
        }
        return "infomanage/add";
    }
}
